import time
import threading
import logging

logger = logging.getLogger('RequestQueue')

class SerialRequest:
    """串口请求类"""
    def __init__(self, client_id, data, response_callback):
        self.client_id = client_id
        self.data = data
        self.response_callback = response_callback
        self.create_time = time.time()
        self.start_time = None
        self.complete = False
        self.response = None

class RequestQueue:
    """串口请求队列"""
    def __init__(self, max_size=10, timeout=3.0):
        self.queue = []
        self.max_size = max_size
        self.timeout = timeout
        self.lock = threading.Lock()
        self.current_request = None
        self.condition = threading.Condition()
        
    def add_request(self, request):
        """添加请求到队列"""
        with self.lock:
            if len(self.queue) >= self.max_size:
                return False
            
            self.queue.append(request)
            # 通知处理线程有新请求
            with self.condition:
                self.condition.notify()
            return True
    
    def get_next_request(self):
        """获取下一个请求"""
        with self.lock:
            if not self.queue:
                return None
            
            # 检查当前请求是否超时
            if self.current_request and not self.current_request.complete:
                elapsed = time.time() - self.current_request.start_time
                if elapsed > self.timeout:
                    logger.warning(f"请求超时: {self.current_request.client_id}")
                    self.current_request.complete = True
                    self.current_request = None
            
            # 如果没有当前请求或当前请求已完成，获取下一个
            if not self.current_request or self.current_request.complete:
                if self.queue:
                    self.current_request = self.queue.pop(0)
                    self.current_request.start_time = time.time()
                    return self.current_request
            
            return None
    
    def complete_request(self, response_data):
        """完成当前请求"""
        with self.lock:
            if self.current_request and not self.current_request.complete:
                self.current_request.complete = True
                self.current_request.response = response_data
                # 调用回调函数返回响应
                if self.current_request.response_callback:
                    self.current_request.response_callback(response_data)
                self.current_request = None
                
                # 通知处理线程请求已完成
                with self.condition:
                    self.condition.notify()
    
    def remove_client_requests(self, client_id):
        """移除特定客户端的请求"""
        with self.lock:
            # 移除队列中的请求
            self.queue = [req for req in self.queue if req.client_id != client_id]
            
            # 如果当前请求是该客户端的，标记为完成
            if self.current_request and self.current_request.client_id == client_id:
                self.current_request.complete = True
                self.current_request = None